﻿using AutoMapper;
using B.S.BasicData.Domain;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interfance;
using B.S.BasicData.Write.Application.Common.Menu;
using MediatR;
using System.Transactions;

namespace B.S.BasicData.Write.Application.Handler.Menu
{
    public class DelMenuHandler : IRequestHandler<DelMenuCommon, ApiResult<int>>
    {
        private readonly IBaseRepository<menuModel> menuRepo;
        private readonly IMapper mapper;

        public DelMenuHandler(IBaseRepository<menuModel> menuRepo,IMapper mapper)
        {
            this.menuRepo = menuRepo;
            this.mapper = mapper;
        }
        public async Task<ApiResult<int>> Handle(DelMenuCommon request, CancellationToken cancellationToken)
        {
            ApiResult<int> res=new ApiResult<int>();
            var result = menuRepo.GetAll().ToList();
            var count = await Del(request.MenuId, result);

           if (count > 0)
            {
                res.Code = ApiEnum.Success;
                res.Message = "删除成功";
                return await Task.FromResult(res);
            }
            else
            {
                res.Code = ApiEnum.Error;
                res.Message = "删除失败";
                return await Task.FromResult(res);
            }
 


        }

        private async Task<int> Del(int menuId, List<menuModel> result)
        {
            int count = 0;
            var res1 = result.FirstOrDefault(x=>x.MenuId== menuId);
            if (res1 != null&&res1.IsDeleted==false)
            {
                res1.IsDeleted = true;
               await menuRepo.Update(res1);
               count++;

                var res = result.Where(x=>x.ParentId==menuId&&x.IsDeleted==false).ToList();
                //有子集
                foreach (var item in res)
                {
                    count += await Del(item.MenuId, result);
                }

            }
            return count;
        }
    }
}
